package handler

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	var food []model.Food
	redis_key := "food_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &food)
	}
	var total int64
	model.DB.Model(&model.Food{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  food,
		"total": total,
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var food []model.Food
	redis_key := "food_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Debug().Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), &food)
	}
	var total int64
	model.DB.Model(&model.Food{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": food,
	})
}

func Add(c *gin.Context) {
	name := c.PostForm("name")
	score := c.PostForm("score")
	address := c.PostForm("address")
	time := c.PostForm("time")

	data := model.Food{
		Name:    name,
		Score:   score,
		Address: address,
		Time:    time,
	}

	err := model.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "food_add" + strconv.Itoa(int(data.ID))
	cache.Rdb.Get(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
